import React, {useEffect} from 'react';
import {useSelector} from "react-redux";
import {Box, Card, CardContent, CardHeader, Chip, Divider, IconButton, Stack, Typography} from "@mui/material";
import CircularProgress from "@mui/material/CircularProgress";
import RefreshIcon from "@mui/icons-material/Refresh";

import {formatHm, today} from "../../utils/time";
import {recent} from "../../api/lesson/lesson-schedule";

const empty = Object.freeze([{uid: 0, name: "", today: [], tomorrow: []}]);

const Lessons = ({date, lessons}) =>
    <Stack direction="row" alignItems="center" spacing={2}>
        <Typography sx={{whiteSpace: "nowrap"}}>{date}</Typography>
        <Box sx={{display: "flex", flexWrap: "wrap", gap: 1, alignItems: "center"}}>
            {lessons.length === 0 ?
                <Chip label="无课"/> :
                lessons.map(lesson =>
                    <Chip color="primary" key={lesson.id} label={`${lesson.course} ${lesson.class} ${lesson.time}`}/>)
            }
        </Box>
    </Stack>;

function RecentLessonSchedule() {

    const user = useSelector(state => state.auth.user);

    const [name, setName] = React.useState("");
    const [loading, setLoading] = React.useState(true);

    /**
     * @typedef {{id: number, course: string, classroom: string, time: string}} Lesson
     * @typedef {{uid: number, username: string, today:Lesson[], tomorrow:Lesson[]}} Value
     * @type {[Value[], React.Dispatch<React.SetStateAction<Value[]>>]}
     */
    const [values, setValues] = React.useState([...empty]);

    useEffect(() => {
        load();
    }, []);

    useEffect(() => {
        if (user) {
            setName(user.name);
        }
    }, [user]);

    function load() {
        setLoading(true);
        recent().then(data => {
                data.length ?
                    setValues(
                        data.reduce((acc, item) => {
                            let v = acc.find(e => e.uid === item.uid);
                            if (!v) {
                                v = {
                                    uid: item.uid,
                                    username: item.username,
                                    today: [],
                                    tomorrow: [],
                                }
                                acc.push(v);
                            }

                            const time = new Date(item.time);
                            const lesson = {
                                id: item.id,
                                course: item.course,
                                class: item.classroom,
                                time: formatHm(time)
                            };
                            today(time) ? v.today.push(lesson) : v.tomorrow.push(lesson);
                            return acc;
                        }, [])) :
                    setValues([...empty]);

                setLoading(false);
            }
        );
    }

    return (
        <Card raised sx={{padding: 2}}>
            <CardHeader
                title={
                    <Stack direction="row" alignItems="center" spacing={1}>
                        <Typography variant="h5">近日课程</Typography>
                        {loading && <CircularProgress color="inherit" size={24}/>}
                    </Stack>
                }
                action={
                    <IconButton onClick={load}><RefreshIcon/></IconButton>
                }
            />
            {values.map(e => <CardContent key={e.uid}>
                <Stack spacing={2}>
                    {e.username && name !== e.username && <Divider>
                        <Chip label={e.username} color="primary"/>
                    </Divider>}
                    <Lessons date="今天" lessons={e.today}/>
                    <Lessons date="明天" lessons={e.tomorrow}/>
                </Stack>
            </CardContent>)}
        </Card>
    );
}

export default RecentLessonSchedule;
